package com.dify.controller;


import com.dify.domain.req.QuestionQueryReq;
import com.dify.domain.req.StopQuestionReq;
import com.dify.domain.resp.StopResponse;
import com.dify.domain.resp.StreamResponse;
import com.dify.service.DifyService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.List;

@RestController
@RequestMapping("/api/dify")
public class DifyController {

    @Value("${dify.key.Deep_Seek_Model}")
    private String Deep_Seek_Model;

    @Value("${dify.key.Big_Model}")
    private String Big_Model;


    @Resource
    private DifyService difyService;

    //可以加限流机制 请求的频率不要太快 避免有人刷资源  这个AOP就你们自己实现吧
    //对前端友好  event 方式 去监听我们的接口   如果用post  前端没办法
    @GetMapping(value = "/stream",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<StreamResponse> streamQuery(QuestionQueryReq req, HttpServletRequest request) {
        String query = req.getQuery();

        if(StringUtils.isEmpty(query)){
            throw new RuntimeException("请输入您的提问哦");
        }

        String ip = request.getRemoteHost(); //其实这个不一定是真的IP  真的IP  X-IP-

        List<String> queryList = req.getQueryList();
        String upContext = "";
        if (!CollectionUtils.isEmpty(queryList)) {
            upContext = queryList.toString();
        }

        String url = req.getType().equals(1) ? Deep_Seek_Model : Big_Model;


        // 使用 Flux 来获取流式响应
        return difyService.streamingMessage(req.getConversation_id(), upContext, query, "lan", url);
    }


    @GetMapping("/stopMessage")
    public StopResponse doStopMessage(StopQuestionReq req,HttpServletRequest request){
        String url = req.getType().equals(1) ? Deep_Seek_Model : Big_Model;

        String ip = request.getRemoteHost();

        return difyService.stopMessage(req.getTaskId(),"lan",url);
    }
}




//produces = MediaType.TEXT_EVENT_STREAM_VALUE


/**
 * location /api/dify/stream {
 *         //别忘了处理跨域问题
 *         proxy IP;  http://localhost:xxxx
 *         //真实IP 要处理
 *
 *         //禁用缓存
 *         proxy_buffering off;
 *         }
 */

